import enquireJs from 'enquire.js'
import Vue from 'vue'
import clonedeep from 'lodash.clonedeep'
export function isDef (v){
  return v !== undefined && v !== null
}

/**
 * Remove an item from an array.
 */
export function remove (arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

export function isRegExp (v) {
  return _toString.call(v) === '[object RegExp]'
}

export function enquireScreen(call) {
  const handler = {
    match: function () {
      call && call(true)
    },
    unmatch: function () {
      call && call(false)
    }
  }
  enquireJs.register('only screen and (max-width: 767.99px)', handler)
}

const _toString = Object.prototype.toString


/**
 * 产生随机整数，包含下限值，包括上限值
 * @param {Number} lower 下限
 * @param {Number} upper 上限
 * @return {Number} 返回在下限到上限之间的一个随机整数
 */
export function random(lower, upper) {
  return Math.floor(Math.random() * (upper - lower + 1)) + lower
}
export function listToTree(list) {
  let temp = clonedeep(list)
  // 将数据存储为 以 id 为 key 的 map 索引数据
  let map = {}
  temp.forEach((item) => {
    map[item.id] = item
  })
  // 把平级变成树
  let resData = []
  temp.forEach(item => {
    let parent = map[item.parentId]
    if (parent) {
      (parent.children || (parent.children = [])).push(item)
    } else {
      resData.push(item)
    }
  })
  // 将树进行排序
  resData.sort((a, b) => a.rank - b.rank)
  function loop(obj) {
    if (obj.children) {
      obj.children.sort((a, b) => a.rank - b.rank)
      obj.children.forEach(item => {
        loop(item)
      })
    }
  }
  resData.forEach(item => {
    loop(item)
  })
  return resData
}


// 导出
export function saveFile(data, name) {
  try {
    const blobUrl = window.URL.createObjectURL(data)
    const a = document.createElement('a')
    a.style.display = 'none'
    a.download = name
    a.href = blobUrl
    a.click()
  } catch (error) {
    Vue.prototype.$message.error('导出文件出错')
  }
}
// 数组对象去重
export function handleArr(arr) {
  let result = []
  let obj = {}
  for (var i = 0; i < arr.length; i++) {
    if (!obj[arr[i].idKey]) {
      result.push(arr[i]);
      obj[arr[i].idKey] = true;
    }
  }
  return result
}
// 项目任务书表格参数标准化
export function standardParams(columns, tableData, filterKey = ['oid']) {
  if (!tableData.length) return []
  let columnsArr = columns.map(item => item.key)
  let standardTableData = []
  tableData.forEach(item => {
    let newItem = {}
    for (let key in item) {
      if (filterKey.includes(key) || columnsArr.includes(key)) {
        if (!item[key] && item[key] !== 0) {
          newItem[key] = ''
        } else {
          newItem[key] = item[key]
        }
      }
    }
    standardTableData.push(newItem)
  })
  return standardTableData
}
